package com.y.fund.aacore.dao;

import java.time.LocalDateTime;
import java.util.concurrent.ThreadLocalRandom;

import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;

/** 实现Hibernate接口的数据库ID生成器; 生成的是全数字的32长度的字符串 */
public class IdGenerator4Hibernate implements IdentifierGenerator{

	private static final long serialVersionUID = 2288138732144890952L;

	private static final int SvrSerial = 1000 + ThreadLocalRandom.current().nextInt(8999);

	private static final int INIT_INCREMENT = 1000000;
	
	private static final int MAX_INCREMENT = 9999966;
	
	private static volatile int adder = INIT_INCREMENT + ThreadLocalRandom.current().nextInt(1000);
	
	private static int increment(){
		synchronized ("idgenerator.inc") {
			if((++adder) > MAX_INCREMENT){
				adder = INIT_INCREMENT + ThreadLocalRandom.current().nextInt(1000);
			}
			return adder;
		}
	}
	@Override
	public Object generate(SharedSessionContractImplementor session, Object object) {
		StringBuffer idStr = new StringBuffer(32);
		LocalDateTime lt = LocalDateTime.now();
		
		idStr.append(lt.getYear());
		if(lt.getMonthValue()<10){
			idStr.append("0");
		}
		idStr.append(lt.getMonthValue());
		
		if(lt.getDayOfMonth()<10){
			idStr.append("0");
		}
		idStr.append(lt.getDayOfMonth());
		
		if(lt.getHour()<10){
			idStr.append("0");
		}
		idStr.append(lt.getHour());
		if(lt.getMinute()<10){
			idStr.append("0");
		}
		idStr.append(lt.getMinute());
		if(lt.getSecond()<10){
			idStr.append("0");
		}
		idStr.append(lt.getSecond());
		
		idStr.append(SvrSerial).append(increment())
			.append(ThreadLocalRandom.current().nextInt(100,999))
			.append(ThreadLocalRandom.current().nextInt(100,999))
			.append(ThreadLocalRandom.current().nextInt(10));
		return idStr.toString();
	
	}

}
